package com.sskj.gocoin.v.fragment;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.design.widget.BottomSheetDialog;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bulong.rudeness.RudenessScreenHelper;
import com.jakewharton.rxbinding2.InitialValueObservable;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.jakewharton.rxbinding2.widget.TextViewAfterTextChangeEvent;
import com.shizhefei.mvc.MVCCoolHelper;
import com.shizhefei.view.coolrefreshview.CoolRefreshView;
import com.sskj.gocoin.R;
import com.sskj.gocoin.R2;
import com.sskj.gocoin.adapter.slimadapter.IViewInjector;
import com.sskj.gocoin.adapter.slimadapter.SlimAdapter;
import com.sskj.gocoin.adapter.slimadapter.SlimInjector;
import com.sskj.gocoin.common.App;
import com.sskj.gocoin.common.Constants;
import com.sskj.gocoin.common.MoneyValueFilter;
import com.sskj.gocoin.common.decoration.DividerLineItemDecoration;
import com.sskj.gocoin.common.rxbus2.RxBus;
import com.sskj.gocoin.common.rxbus2.Subscribe;
import com.sskj.gocoin.common.rxbus2.ThreadMode;
import com.sskj.gocoin.component.DaggerUserDataComponent;
import com.sskj.gocoin.m.bean.FabiListBean;
import com.sskj.gocoin.mvchelper.ModelRx2DataSource;
import com.sskj.gocoin.p.fragment.FabiBuyPresenter;
import com.sskj.gocoin.utils.BottomUpUtil;
import com.sskj.gocoin.utils.CheckUtil;
import com.sskj.gocoin.utils.ClickUtil;
import com.sskj.gocoin.utils.MathUtil;
import com.sskj.gocoin.utils.NumberUtil;
import com.sskj.gocoin.utils.ToastUtil;
import com.sskj.gocoin.v.activity.FabiSellDetail2Activity;
import com.sskj.gocoin.v.activity.MainActivity;
import com.sskj.gocoin.v.activity.SecurityCenterActivity;
import com.sskj.gocoin.v.base.BaseFragment;
import com.sskj.lib.RConfig;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Observable;


public class FabiBuyAndSellFragment extends BaseFragment<MainActivity, FabiBuyPresenter> {

    @BindView(R2.id.tv_money)
    TextView tvMoney;
    @BindView(R2.id.iv_money_arrow)
    ImageView ivMoneyArrow;
    @BindView(R2.id.iv_pay_type_arrow)
    ImageView ivPayTypeArrow;
    @BindView(R2.id.tv_pay_type)
    TextView tvPayType;
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.coolRefreshView)
    CoolRefreshView coolRefreshView;
    private SlimAdapter slimAdapter;
    private int curPos;
    private BottomSheetDialog sellDialog;
    private BottomSheetDialog codeDialog;
    private TextView tvSaleName;
    private TextView tvPerPrice;
    private TextView tvPriceTab;
    private View viewPrice;
    private View viewNum;
    private TextView tvNumTab;
    private EditText etPrice;
    private EditText etPayPwd;
    private TextView tvTypeAllPrice;
    private TextView tvTypeAllNum;
    private TextView tvLimitPrice;
    private boolean isPrice = true;
    private boolean isBuy;
    private View llPrice;
    private View llNum;
    private EditText etNum;
    private TextView tvSellNum;
    private TextView tvSellPrice;
    private FabiListBean dataItem;
    private String num = "0.0000";
    private String price = "0.00";
    private Button btDeal;
    private MVCCoolHelper<List<FabiListBean>> mvcCoolHelper;
    @Inject
    UserViewModel userViewModel;
    private UserData userData;

    public static FabiBuyAndSellFragment newInstance(boolean isBuy) {

        Bundle args = new Bundle();
        args.putBoolean(Constants.IS_BUY, isBuy);
        FabiBuyAndSellFragment fragment = new FabiBuyAndSellFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public int getLayoutId() {
        return R.layout.fragment_fabi_buy;
    }

    @Override
    public FabiBuyPresenter getPresenter() {
        return new FabiBuyPresenter();
    }

    @Override
    public void initView() {
        RxBus.getDefault().register(this);
        DaggerUserDataComponent.create().inject(this);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
            } else {
                userData = null;
            }
        });
        isBuy = getArguments().getBoolean(Constants.IS_BUY);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.addItemDecoration(new DividerLineItemDecoration(getActivity())
                .setFirstDraw(false)
                .setPaintWidth((int) RudenessScreenHelper.pt2px(getActivity(), 20))
                .setDividerColor(ContextCompat.getColor(getContext(), R.color.transparent)));
        slimAdapter = SlimAdapter.create().register(R.layout.recy_item_fabi, new SlimInjector<FabiListBean>() {
            @Override
            public void onInject(FabiListBean data, IViewInjector injector) {
                injector.clicked(R.id.bt_sale, v -> {
                    if (userData != null) {
                        if (!userData.getAccount().equals(data.getAccount())) {
                            if (checkIdent(getContext())) {
                                if (checkPwdStatus()) {
                                    curPos = slimAdapter.getData().indexOf(data);
                                    if (isBuy) {
                                        if (checkIdentHign(getActivity())) {
                                            if (userData.getPay_list() > 0) {
                                                showSell();
                                            } else {
                                                ToastUtil.showShort(App.INSTANCE.getString(R.string.fabimineJavaFabiBuyAndSellFragment3));
                                                ARouter.getInstance().build(RConfig.MINE_SECURITY).navigation();
                                            }
                                        }
                                    } else {
                                        showSell();
                                    }

                                }
                            }

                        } else {
                            ToastUtil.showShort(App.INSTANCE.getString(R.string.strFabiBuyAndSellFragment204));
                        }
                    } else {
                        ToastUtil.showShort(App.INSTANCE.getString(R.string.strFabiBuyAndSellFragment205));
                        ARouter.getInstance().build(RConfig.APP_LOGIN).navigation();
                        getActivity().overridePendingTransition(R.anim.lib_anim_in, R.anim.lib_anim_out);

                    }
                }).text(R.id.tv_name, data.getRealname())
                        .text(R.id.tv_money, data.getCd_num())
                        .text(R.id.tv_percent, data.getRate())
                        .text(R.id.tv_num, data.getAmount())  // 剩余数量
                        .text(R.id.tv_limit_money, data.getLimitNum())
                        .text(R.id.tv_china_money, data.getPrice())
                        .text(R.id.tv_photo, getFirstName(data.getRealname()))
                        .text(R.id.bt_sale, isBuy ? App.INSTANCE.getString(R.string.strFabiBuyAndSellFragment206) : App.INSTANCE.getString(R.string.strFabiBuyAndSellFragment207))
                        .background(R.id.bt_sale, isBuy ? R.drawable.green_bg : R.drawable.red_bg)
                        .visibility(R.id.iv_wechat, "1".equals(data.getPay_wx()) ? View.VISIBLE : View.GONE)
                        .visibility(R.id.iv_bank, "1".equals(data.getPay_backcard()) ? View.VISIBLE : View.GONE)
                        .visibility(R.id.iv_alipay, "1".equals(data.getPay_alipay()) ? View.VISIBLE : View.GONE)
                        .visibility(R.id.iv_pay_pal, "1".equals(data.getPaypal()) ? View.VISIBLE : View.GONE);
            }
        });
        slimAdapter.attachTo(recyclerView).updateData(new ArrayList());
        ModelRx2DataSource<FabiListBean> dataSource =
                new ModelRx2DataSource<>((ModelRx2DataSource.OnLoadSource<FabiListBean>)
                        page -> mPresenter.getFabiList(page, Constants.PAGE_SIZE, isBuy), Constants.PAGE_SIZE);
        mvcCoolHelper = new MVCCoolHelper<>(coolRefreshView);
        mvcCoolHelper.setDataSource(dataSource);
        mvcCoolHelper.setAdapter(slimAdapter);
        mvcCoolHelper.refresh();
    }

    private String getFirstName(String realname) {
        if (TextUtils.isEmpty(realname)) {
            return "";
        } else {
            return realname.charAt(0) + "";
        }
    }

    /**
     * 显示支付方式
     */
    private void showPayType() {
        View popupView = LayoutInflater.from(getActivity()).inflate(R.layout.popup_fabi_pay_type, null);
        PopupWindow popupWindow = new PopupWindow(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setContentView(popupView);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
        popupWindow.setOutsideTouchable(true);
//        popupWindow.setAnimationStyle(R.style.AnimDown);
        popupWindow.setClippingEnabled(true);

        popupWindow.showAsDropDown(tvMoney);
    }

    /**
     * 显示销售底部弹窗
     */
    private void showSell() {
        dataItem = (FabiListBean) slimAdapter.getDataItem(curPos);
        sellDialog = new BottomSheetDialog(getActivity());
        View dialogView = LayoutInflater.from(getActivity()).inflate(R.layout.bottom_sheet_fabi_sell, null);
        btDeal = dialogView.findViewById(R.id.bt_deal);
        tvSaleName = dialogView.findViewById(R.id.tv_sale_name);
        tvPerPrice = dialogView.findViewById(R.id.tv_per_price);
        tvPriceTab = dialogView.findViewById(R.id.tv_price_tab);  // 法币计价
        tvNumTab = dialogView.findViewById(R.id.tv_num_tab);  //出售数量
        viewPrice = dialogView.findViewById(R.id.view_price);
        viewNum = dialogView.findViewById(R.id.view_num);
        etPrice = dialogView.findViewById(R.id.et_price);  // 价格输入框
        etPayPwd = dialogView.findViewById(R.id.et_pay_pwd);  // 价格输入框
        etNum = dialogView.findViewById(R.id.et_num);  // 数量输入框
        tvTypeAllPrice = dialogView.findViewById(R.id.tv_type_all_price);
        tvTypeAllNum = dialogView.findViewById(R.id.tv_type_all_num);
        tvLimitPrice = dialogView.findViewById(R.id.tv_limit_price);
        llPrice = dialogView.findViewById(R.id.ll_price);
        llNum = dialogView.findViewById(R.id.ll_num);
        tvSellNum = dialogView.findViewById(R.id.tv_sell_num);   // 实际购买/出售
        tvSellPrice = dialogView.findViewById(R.id.tv_sell_price);  //交易金额
        ClickUtil.click(btDeal, () -> {
            if (Double.valueOf(num) == 0 || Double.valueOf(price) == 0) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.strFabiBuyAndSellFragment213));
                return;
            }
            if (Double.valueOf(price) < Double.valueOf(dataItem.getMin_price())) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.strFabiBuyAndSellFragment214) + dataItem.getMin_price());
                return;
            }
            if (Double.valueOf(price) > Double.valueOf(dataItem.getMax_price())) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.strFabiBuyAndSellFragment215) + dataItem.getMax_price());
                return;
            }
            if (Double.valueOf(num) > Double.valueOf(dataItem.getOriginAmount())) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.strFabiBuyAndSellFragment216));
                return;
            }
            if (TextUtils.isEmpty(etPayPwd.getText().toString())) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.fabimineJavaFabiBuyAndSellFragment10));
                return;
            }
            if (!CheckUtil.isPayPwd(etPayPwd.getText().toString())) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.strBottomUpUtil201));
                return;
            }
            btDeal.setEnabled(false);
            mPresenter.order(etPayPwd.getText().toString(),
                    dataItem.getOrder_no(),
                    NumberUtil.keepNoZore(num),
                    NumberUtil.keepNoZore(price), isBuy);
//            showCode();
        });
        sellDialog.setContentView(dialogView);
        ViewGroup group = (ViewGroup) dialogView.getParent();
        group.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.transparent));
        ClickUtil.click(tvNumTab, () -> {
            isPrice = false;
            changeTab();
        });
        ClickUtil.click(tvPriceTab, () -> {
            isPrice = true;
            changeTab();
        });
        //默认数量
        isPrice = false;
        changeTab();
        etNum.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(4)});
        etPrice.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(4)});
        InitialValueObservable<TextViewAfterTextChangeEvent> numFlow = RxTextView.afterTextChangeEvents(etNum);
        InitialValueObservable<TextViewAfterTextChangeEvent> priceFlow = RxTextView.afterTextChangeEvents(etPrice);
        Observable.merge(numFlow, priceFlow)
                .subscribe(textViewAfterTextChangeEvent -> changeResult());
        tvSaleName.setText(isBuy ? App.INSTANCE.getString(R.string.strFabiBuyAndSellFragment217) : App.INSTANCE.getString(R.string.strFabiBuyAndSellFragment218));
        tvPerPrice.setText(dataItem.getPrice());
        tvNumTab.setText(isBuy ? App.INSTANCE.getString(R.string.strFabiBuyAndSellFragment219) : App.INSTANCE.getString(R.string.strFabiBuyAndSellFragment220));
        etPrice.setHint(isBuy ? App.INSTANCE.getString(R.string.strFabiBuyAndSellFragment221) : App.INSTANCE.getString(R.string.strFabiBuyAndSellFragment222));
        etNum.setHint(isBuy ? App.INSTANCE.getString(R.string.strFabiBuyAndSellFragment223) : App.INSTANCE.getString(R.string.strFabiBuyAndSellFragment224));
        tvTypeAllPrice.setText(isBuy ? App.INSTANCE.getString(R.string.strFabiBuyAndSellFragment225) : App.INSTANCE.getString(R.string.strFabiBuyAndSellFragment226));
        tvTypeAllNum.setText(isBuy ? App.INSTANCE.getString(R.string.strFabiBuyAndSellFragment225) : App.INSTANCE.getString(R.string.strFabiBuyAndSellFragment226));
        btDeal.setBackground(ContextCompat.getDrawable(getActivity(), isBuy ? R.drawable.green_bg : R.drawable.red_bg));
        ClickUtil.click(tvTypeAllPrice, () -> {
            etPrice.setText(dataItem.getMax_price());
        });
        ClickUtil.click(tvTypeAllNum, () -> {
            etNum.setText(Double.parseDouble(MathUtil.divide(dataItem.getMax_price(), dataItem.getOriginPrice(), 4, BigDecimal.ROUND_FLOOR)) < Double.parseDouble(dataItem.getAmount().replace(App.INSTANCE.getString(R.string.strFabiBuyAndSellFragment229), "").replace("USDT", "")) ? MathUtil.divide(dataItem.getMax_price(), dataItem.getOriginPrice(), 4, BigDecimal.ROUND_FLOOR) : dataItem.getAmount());
        });
        tvLimitPrice.setText("￥" + dataItem.getMin_price() + "-￥" + dataItem.getMax_price());
        sellDialog.show();
    }

    /**
     * 根据法币计价和出售数量计算总的数量与价格
     */
    private void changeResult() {
        num = etNum.getText().toString();
        price = etPrice.getText().toString();

        if (isPrice) {
            if (TextUtils.isEmpty(price)) {
                num = "0.0000";
                price = "0.00";
            } else {
                num = "" + MathUtil.divide(price, dataItem.getOriginPrice(), 4);
            }
        } else {
            if (TextUtils.isEmpty(num)) {
                num = "0.0000";
                price = "0.00";
            } else {
                price = "" + MathUtil.multiply(Double.valueOf(num), Double.valueOf(dataItem.getOriginPrice()));
            }
        }
        tvSellNum.setText((isBuy ? App.INSTANCE.getString(R.string.strFabiBuyAndSellFragment239) : App.INSTANCE.getString(R.string.strFabiBuyAndSellFragment240)) + num + " USDT");
        price = String.valueOf(MathUtil.round(price, 2));
        tvSellPrice.setText("￥" + price);
    }

    private void changeTab() {
        tvPriceTab.setTextColor(getResources().getColor(isPrice ? R.color.white : R.color.fabi_item_text_color));
        viewPrice.setVisibility(isPrice ? View.VISIBLE : View.INVISIBLE);
        tvNumTab.setTextColor(getResources().getColor((!isPrice) ? R.color.white : R.color.fabi_item_text_color));
        viewNum.setVisibility(!isPrice ? View.VISIBLE : View.INVISIBLE);
        if (isPrice) {
            llPrice.setVisibility(View.VISIBLE);
            llNum.setVisibility(View.GONE);
        } else {
            llPrice.setVisibility(View.GONE);
            llNum.setVisibility(View.VISIBLE);
        }
        changeResult();
    }

    private void showPricePop() {
        View popupView = LayoutInflater.from(getActivity()).inflate(R.layout.popup_fabi_price, null);
        PopupWindow popupWindow = new PopupWindow(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setContentView(popupView);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0x66000000));
        popupWindow.setOutsideTouchable(true);
//        popupWindow.setAnimationStyle(R.style.AnimDown);
        popupWindow.setClippingEnabled(true);

        popupWindow.showAsDropDown(tvMoney);
    }

    /**
     * 显示验证码底部弹窗
     */
    private void showCode() {
        codeDialog = BottomUpUtil.getPay(getActivity(), mPresenter, (pwd) -> {
            mPresenter.order(pwd, dataItem.getOrder_no(), NumberUtil.keepNoZore(num), NumberUtil.keepNoZore(price), isBuy);
        });
        codeDialog.show();
    }

    public void checkOk(String orderNum, boolean isBuy) {
//        codeDialog.dismiss();
        sellDialog.dismiss();
        mvcCoolHelper.refresh();
        FabiSellDetail2Activity.start(getActivity(), orderNum, !isBuy);
    }

    /**
     * 刷新数据
     */
    @Subscribe(code = Constants.FABI_DATING_REFRESH, threadMode = ThreadMode.MAIN)
    public void refresh() {
        if (mvcCoolHelper != null) {
            mvcCoolHelper.refresh();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unregister(this);
    }

    public boolean checkPwdStatus() {
        if (userData != null) {
            if (userData.getTpwd() != null && userData.getTpwd().equals("1")) {
                return true;
            } else {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.strMainActivity218));
                startActivity(new Intent(getActivity(), SecurityCenterActivity.class));
                return false;
            }
        }
        return false;
    }

    public void setEnable() {
        btDeal.setEnabled(true);
    }
}
